/*******************************************************************************
 * Copyright (c) 2008, 2009 Fabio Mauro - Alberto Terraneo.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.2
 * or any later version published by the Free Software Foundation.
 *     
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied 
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU Free Documentation License for more details.
 *     
 * You should have received a copy of the GNU Free Documentation 
 * License along with this distribution; if not, send a email to authors:
 * aterraneo <at> users.sourceforge.net
 * bigmoby09 <at> users.sourceforge.net
 *******************************************************************************/
package it.blueocean.acanto.security.model;

import java.util.Collection;

import org.apache.wicket.security.hive.authentication.DefaultSubject;
import org.apache.wicket.security.hive.authorization.Principal;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class SpringSecuritySubject extends DefaultSubject
{
	private static final long serialVersionUID = -3930251681474159099L;

	/**
	 * Constructor.
	 */
	public SpringSecuritySubject()
	{
		Collection<GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
		
		if (authorities != null)
		{
			Principal principal;
			
			for (GrantedAuthority grantedAuthority : authorities)
			{
				principal = convert(grantedAuthority);
				
				if (principal != null)
				{					
					addPrincipal(principal);
				}
			}
		}
	}

	/**
	 * Converts a {@link GrantedAuthority} to a {@link Principal}
	 * 
	 * @param authority
	 * @return principal or null if the authority could not be converted
	 */
	protected Principal convert(GrantedAuthority authority)
	{
		return new MyPrincipal(authority.getAuthority());
	}

}
